const fs = require('fs');
const path = require('path');
const { minify } = require('terser');
const CleanCSS = require('clean-css');

// 创建构建目录
const buildDir = path.join(__dirname, 'dist');
if (!fs.existsSync(buildDir)) {
    fs.mkdirSync(buildDir, { recursive: true });
}

// 压缩CSS
async function minifyCSS() {
    const cssFiles = ['styles.css'];
    
    for (const file of cssFiles) {
        const filePath = path.join(__dirname, file);
        if (fs.existsSync(filePath)) {
            const css = fs.readFileSync(filePath, 'utf8');
            const minified = new CleanCSS({
                level: 2,
                format: 'keep-breaks'
            }).minify(css);
            
            fs.writeFileSync(path.join(buildDir, file), minified.styles);
            console.log(`✓ CSS压缩完成: ${file}`);
        }
    }
}

// 压缩JavaScript
async function minifyJS() {
    const jsFiles = ['script.js', 'script-new.js'];
    
    for (const file of jsFiles) {
        const filePath = path.join(__dirname, file);
        if (fs.existsSync(filePath)) {
            const code = fs.readFileSync(filePath, 'utf8');
            const result = await minify(code, {
                compress: {
                    drop_console: true,
                    drop_debugger: true
                },
                mangle: {
                    toplevel: true
                }
            });
            
            fs.writeFileSync(path.join(buildDir, file), result.code);
            console.log(`✓ JavaScript压缩完成: ${file}`);
        }
    }
}

// 复制并优化HTML文件
function optimizeHTML() {
    const htmlFiles = ['index.html', 'blog.html', 'editor.html', 'login.html'];
    
    for (const file of htmlFiles) {
        const filePath = path.join(__dirname, file);
        if (fs.existsSync(filePath)) {
            let html = fs.readFileSync(filePath, 'utf8');
            
            // 简单的HTML压缩
            html = html
                .replace(/\s+/g, ' ')
                .replace(/>\s+</g, '><')
                .replace(/<!--[\s\S]*?-->/g, '');
            
            // 替换资源引用为压缩版本
            html = html
                .replace('styles.css', 'styles.min.css')
                .replace('script.js', 'script.min.js')
                .replace('script-new.js', 'script-new.min.js');
            
            fs.writeFileSync(path.join(buildDir, file), html);
            console.log(`✓ HTML优化完成: ${file}`);
        }
    }
}

// 生成WebP图片（模拟函数）
function generateWebPImages() {
    const images = ['Logo.png'];
    
    for (const img of images) {
        const imgPath = path.join(__dirname, img);
        if (fs.existsSync(imgPath)) {
            // 在实际项目中，这里应该使用sharp等库转换图片
            console.log(`⚠ 需要手动转换图片为WebP: ${img}`);
        }
    }
}

// 生成构建报告
function generateBuildReport() {
    const report = {
        timestamp: new Date().toISOString(),
        files: []
    };
    
    const files = fs.readdirSync(buildDir);
    files.forEach(file => {
        const stats = fs.statSync(path.join(buildDir, file));
        report.files.push({
            name: file,
            size: stats.size,
            sizeKB: (stats.size / 1024).toFixed(2)
        });
    });
    
    fs.writeFileSync(path.join(buildDir, 'build-report.json'), JSON.stringify(report, null, 2));
    console.log('✓ 构建报告生成完成');
}

// 主构建函数
async function build() {
    console.log('🚀 开始构建前端资源...\n');
    
    try {
        await minifyCSS();
        await minifyJS();
        optimizeHTML();
        generateWebPImages();
        generateBuildReport();
        
        console.log('\n🎉 构建完成！');
        console.log('📁 输出目录:', buildDir);
    } catch (error) {
        console.error('❌ 构建失败:', error);
    }
}

// 执行构建
if (require.main === module) {
    build();
}

module.exports = { build };